#pragma once
#include<iostream>
#include<queue>
#include<pthread.h>
using namespace std;

const int max_queue_size=5;
template<class T>
class BlockQueue
{
public:
    BlockQueue(int cap=max_queue_size)
    :_max_cap(cap)
    {
        pthread_mutex_init(&_mutex,nullptr);
        pthread_cond_init(&_c_cond,nullptr);
        pthread_cond_init(&_p_cond,nullptr);
    }

    ~BlockQueue()
    {
        pthread_mutex_destroy(&_mutex);
        pthread_cond_destroy(&_c_cond);
        pthread_cond_destroy(&_p_cond);
    }

    bool IsEmpty()
    {
        return _q.empty();
    }

    bool IsFull()
    {
        return _q.size()==_max_cap;
    }

    void Push(const T& val)
    {
        pthread_mutex_lock(&_mutex);
        while(IsFull())
        {
            pthread_cond_wait(&_c_cond,&_mutex);
        }
        _q.push(val);
        pthread_mutex_unlock(&_mutex);
        pthread_cond_signal(&_p_cond);
    }

    void Pop(T* out)
    {
        pthread_mutex_lock(&_mutex);
        while(IsEmpty())
        {
            pthread_cond_wait(&_p_cond,&_mutex);
        }
        *out=_q.front();
        _q.pop();
        pthread_mutex_unlock(&_mutex);

        pthread_cond_signal(&_c_cond);
    }

private:
    queue<T> _q;
    int _max_cap;

    pthread_mutex_t _mutex;
    pthread_cond_t _c_cond;
    pthread_cond_t _p_cond;
};